﻿using System;
using System.Linq;
using System.Web.Mvc;
using MvcContrib.PortableAreas;
using MvcContrib.Sorting;
using MvcContrib.UI.Grid;
using QDT.Common;
using QDT.Core.Members;
using QDT.Core.Projects;
using QDT.Lang;
using QDT.MVC.Security;
using QDT.Services.Projects;
using QDT.Web.Admin.Models;
using QDT.Common.Data;

namespace QDT.Web.Admin.Controllers
{
    [SecurityModule(Name = "贷款管理")]
    public class LoanController : BaseController
    {

        [SecurityNode(Name = "贷款列表")]
        public ActionResult Index(int? page, GridSortOptions sort, int? id, string name, string username, int? typeId, int? repayTime)
        {
            User user = null;

            if (!string.IsNullOrWhiteSpace(username))
            {
                user = DbProvider.D<User>().FirstOrDefault(x => x.UserName == username);
            }

            ViewData["ProjectTypes"] = DbProvider.D<ProjectType>().Where(x => !x.IsDelete).ToList();

            var filter = PredicateExtensionses.True<ParentProject>();

            if (repayTime != null && repayTime != 0) filter = filter.And(x => x.RepayTime == repayTime);

            if (id != null && id != 0) filter = filter.And(x => x.ID == id);

            if (!string.IsNullOrEmpty(name)) filter = filter.And(x => x.Name.Contains(name));

            if (typeId != null && typeId > 0) filter = filter.And(x => x.TypeId == typeId);

            if (user != null) filter = filter.And(x => x.UserId == user.ID);

            const int pageSize = 20;

            var pageNumber = page ?? 1;

            if (sort.Column == null) sort.Column = "ID";

            ViewData["sort"] = sort;

            var deals = DbProvider.D<ParentProject>().Where(filter.And(x => !x.IsDelete)).OrderBy(sort.Column, sort.Direction == SortDirection.Descending);

            return View(deals.ToPagedList(pageNumber - 1, pageSize));

        }

        [SecurityNode(Name = "添加贷款")]
        public ActionResult AddLoan()
        {
            var types = DbProvider.D<ProjectType>().Where(x => !x.IsDelete && x.IsEffect).ToList();
            var agencys = DbProvider.D<ProjectAgency>().ToList();

            ViewData["ProjectTypes"] = types;
            ViewData["ProjectAgencys"] = agencys;

            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        [SecurityNode(Name = "添加贷款操作")]
        public ActionResult PostAddLoan(NewLoanModel model)
        {
            if (!ModelState.IsValid) return Error();

            if (model.BorrowAmount <= 0) return Error("借款金额不能小于0");

            if (model.RepayTime <= 0) return Error("借款期限不能小于0");

            if (model.Rate <= 0) return Error("利率不能小于0");

            var type = DbProvider.GetByID<ProjectType>(model.TypeId);

            if (type == null) return Error("项目类型不存在");

            var loan = new ParentProject
            {

                Name = model.Name,
                SubName = model.SubName,
                TypeId = model.TypeId,
                AgencyId = model.AgencyId,
                UserId = model.UserId,
                RepaymentId = model.RepaymentId,
                Description = model.Description,
                IsEffect = model.IsEffect,
                IsDelete = false,
                Sort = model.Sort,
                BorrowAmount = model.BorrowAmount,
                RepayTime = model.RepayTime,
                RepayTimeType = model.RepayTimeType,
                Rate = model.Rate,
                EndDate = model.EndDate,
                CreateTime = DateTime.Now,
                SettleDay = model.SettleDay,
                Warrant = model.Warrant,
                TotalBorrow = model.BorrowAmount.ToString(),
                LoanPurpose = model.LoanPurpose,
                Industry = model.Industry,
                IndustryDetail = model.IndustryDetail,
                LoanInfo = model.LoanInfo,
                ProjectProcess = model.ProjectProcess,
                RiskControl = model.RiskControl,
                
            };

            DbProvider.Add(loan);
            DbProvider.SaveChanges();

            return Success("添加成功");
        }

        [SecurityNode(Name = "编辑贷款页")]
        public ActionResult EditLoan(int id)
        {
            var loan = DbProvider.GetByID<ParentProject>(id);

            if (loan == null) return Error("项目不存在");

            var types = DbProvider.D<ProjectType>().Where(x => !x.IsDelete && x.IsEffect).ToList();
            var agencys = DbProvider.D<ProjectAgency>().ToList();

            ViewData["ProjectTypes"] = types;
            ViewData["ProjectAgencys"] = agencys;

            return View(loan);
        }

        [HttpPost]
        [SecurityNode(Name = "编辑贷款操作")]
        [ValidateInput(false)]
        public ActionResult PostEditLoan(NewLoanModel model)
        {
            var loan = DbProvider.GetByID<ParentProject>(model.ID);
            if (loan == null) return Error("无效ID");

            loan.Name = model.Name;
            loan.SubName = model.SubName;
            loan.TypeId = model.TypeId;
            loan.UserId = model.UserId;
            loan.RepaymentId = model.RepaymentId;
            loan.AgencyId = model.AgencyId;
            loan.IsEffect = model.IsEffect;
            loan.Sort = model.Sort;
            loan.BorrowAmount = model.BorrowAmount;
            loan.RepayTime = model.RepayTime;
            loan.RepayTimeType = model.RepayTimeType;

            loan.Rate = model.Rate;
            loan.EndDate = model.EndDate;
            loan.SettleDay = model.SettleDay;
            loan.Warrant = model.Warrant;
            loan.TotalBorrow = model.BorrowAmount.ToString();
            loan.LoanPurpose = model.LoanPurpose;

            loan.Description = model.Description;
            loan.Industry = model.Industry;
            loan.IndustryDetail = model.IndustryDetail;
            loan.LoanInfo = model.LoanInfo;
            loan.ProjectProcess = model.ProjectProcess;
            loan.RiskControl = model.RiskControl;
                
            DbProvider.SaveChanges();

            return Success("编辑成功");
        }

        [SecurityNode(Name = "图片")]
        public ActionResult Images(int id)
        {

            var result = IoC.Resolve<ProjectService>().GetProjectImages(id);

            return View(result);
        }

        [SecurityNode(Name = "添加图片页")]
        public ActionResult AddImage(int id, string title)
        {
            ViewBag.T = title;
            return View();
        }

        [HttpPost]
        [SecurityNode(Name = "添加图片操作")]
        public ActionResult PostAddImage(int pid, string title, string thumbnail, string photo, int sort)
        {

            var img = new ProjectImage(pid, title+DateTime.Now.ToString("ddHHmmss"), photo, sort)
            {
                Thumbnail = thumbnail
            };
            DbProvider.Add(img);

            DbProvider.SaveChanges();

            return Success("操作成功");
        }

        [SecurityNode(Name = "删除图片")]
        public ActionResult DeleteImage(int[] id)
        {
            foreach (var i in id)
            {

                var feild = DbProvider.GetByID<ProjectImage>(i);

                if (feild == null) continue;

                DbProvider.Delete(feild);
            }

            DbProvider.SaveChanges();

            return Success("操作成功");
        }

        [SecurityNode(Name = "编辑图片页")]
        public ActionResult EditImage(int id)
        {
            var img = DbProvider.GetByID<ProjectImage>(id);
            if (img == null) return Error("资源不存在");

            return View(img);
        }

        [HttpPost]
        [SecurityNode(Name = "编辑图片操作")]
        public ActionResult PostEditImage(int id, string title, string thumbnail, string photo, int sort)
        {
            var img = DbProvider.GetByID<ProjectImage>(id);
            if (img == null) return Error("资源不存在");

            img.Title = title;
            img.Thumbnail = thumbnail;
            img.Photo = photo;
            img.Sort = sort;

            DbProvider.SaveChanges();

            return Success("操作成功");
        }

    }
}
